package tw.asap.plus.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.request.ShopSearchBean;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.MerchantService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.adapter.MerchantListAdapter;
import tw.asap.plus.ui.custom.CategorySelectorView;
import tw.asap.plus.utils.SPUtil;
import tw.asap.plus.utils.T;

/**
 * Description:
 * Created:      [15/11/18]
 * Author:       [Yang]
 **/
public class SearchActivity extends AsapBaseActivity {


    @InjectView(R.id.iv_navigation_header_left)
    ImageView ivNavigationHeaderLeft;
    @InjectView(R.id.ll_navigation_left)
    RelativeLayout llNavigationLeft;
    @InjectView(R.id.tv_search_view)
    EditText tvSearchView;
    @InjectView(R.id.layout_navigation_header)
    RelativeLayout layoutNavigationHeader;
    @InjectView(R.id.category_name)
    TextView categoryName;

    CategorySelectorView selectorView;
    @InjectView(R.id.rv_base_list_fragment)
    RecyclerView recyclerView;
    @InjectView(R.id.srl_base_list_fragment)
    FrameLayout swipeRefreshLayout;
    @InjectView(R.id.extra_layout)
    FrameLayout extraLayout;
    private MerchantListAdapter adapter;
    private ArrayList<ShopIndex.ShopEntity> dataList = new ArrayList<>();

    int currentCategory = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_search);
        ButterKnife.inject(this);
        setUpHeadView();
    }


    private void setUpHeadView() {
        tvSearchView.addTextChangedListener(searchWatcher);
        tvSearchView.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                displayExtraLayout(0);
                searchKeywords(v.getText().toString());
                return true;
            }
            return false;
        });
        selectorView = new CategorySelectorView(this);
        selectorView.setItemClickListener((parent, view, position, id) -> {
            currentCategory = position;
            switch (position) {
                case 0:
                    categoryName.setText(getString(R.string.shop));
                    break;
                case 1:
                    categoryName.setText(getString(R.string.goods));
                    break;
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (selectorView != null) {
            selectorView.dismiss();
        }
    }

    @OnClick(R.id.ll_navigation_left)
    protected void onBack(){
        finish();
    }

    @OnClick(R.id.category_name)
    protected void onClickCategory() {
        selectorView.showAsDropDown(categoryName);
    }

    TextWatcher searchWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(s)) {
                searchKeywords(s.toString());
                displayExtraLayout(0);
            }
        }
    };

    private void searchKeywords(String keywords) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<ShopIndex.ShopEntity>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<ShopIndex.ShopEntity>>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);
                String lat = SPUtil.getInstance(SearchActivity.this).getString(ConstValue.Sp.LAT, "0");
                String lng = SPUtil.getInstance(SearchActivity.this).getString(ConstValue.Sp.LNG, "0");
                ResponseDataWrapper<List<ShopIndex.ShopEntity>> responseDataWrapper = null;
                switch (currentCategory){
                    case 0:
                        responseDataWrapper = service.searchShop(new ShopSearchBean(lat, lng, keywords));
                        break;
                    case 1:
                        responseDataWrapper = service.searchGoods(new ShopSearchBean(lat, lng, keywords));
                        break;
                }
                subscriber.onNext(responseDataWrapper);
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<ShopIndex.ShopEntity>>>() {
                               @Override
                               public void onCompleted() {
                               }

                               @Override
                               public void onError(Throwable e) {
                                   T.e(e.toString());
                                   displayExtraLayout(2);
                               }

                               @Override
                               public void onNext(ResponseDataWrapper<List<ShopIndex.ShopEntity>> responseDataWrapper) {
                                   if (responseDataWrapper.respcd.equals(ConstValue.RESPCD)) {
                                       if (responseDataWrapper.data.size() == 0) {
                                           displayExtraLayout(1);
                                       } else {
                                           if (adapter == null) {
                                               dataList.addAll(responseDataWrapper.data);
                                               initRecyclerView(dataList);
                                           } else {
                                               extraLayout.setVisibility(View.GONE);
                                               swipeRefreshLayout.setVisibility(View.VISIBLE);
                                               dataList.clear();
                                               dataList.addAll(responseDataWrapper.data);
                                           }
                                           adapter.notifyDataSetChanged();
                                       }
                                   }
                               }
                           }

                );
    }

    private void initRecyclerView(List<ShopIndex.ShopEntity> list) {
        extraLayout.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        adapter = new MerchantListAdapter(this, list);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);
    }

    private void displayExtraLayout(int type) {
        if (extraLayout.getChildCount() > 0) {
            extraLayout.removeAllViews();
        }
        extraLayout.setVisibility(View.VISIBLE);
        switch (type) {
            case 0://loading
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_searching, extraLayout);
                break;
            case 1://noData
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_search_noresult, extraLayout);
                break;
            case 2://noNetwork
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(this).inflate(R.layout.layout_nonetwork, extraLayout);
                break;
        }
    }

}
